<template>
  <div class="warpper">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="Category Name">
          <el-input v-model="searchForm.name" @keyup.enter.native="search" placeholder="Enter Name">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="find()" plain style="margin-left: 24px;">Search</el-button>
          <el-button v-permission="['product_categories.store']" type="primary" plain @click="adda()">+ New</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table :data="tableData" size="small" stripe border style="width: 100%">
        <el-table-column type="selection" width="50" align="center" />
        <!-- <el-table-column prop="id" label="id" min-width="100" align="center" /> -->
        <el-table-column prop="name" label="Category Name" min-width="150" align="center" sortable/>
        <el-table-column prop="level" label="Level" min-width="120" align="center" sortable/>
        <el-table-column prop="productnumber" label="Products QTY" min-width="150" align="center" sortable/>

        <el-table-column prop="parentname" label="Parent Product Category" min-width="200" align="center" sortable>
          <template v-slot="scope">
            <span>{{ scope.row.parentname?scope.row.parentname:"None"}}</span>
          </template>
        </el-table-column>

        <el-table-column prop="adminame" label="Staff" min-width="150" align="center" sortable/>
        <el-table-column prop="created_at" label="Created Time" min-width="200" align="center" sortable>
          <template v-slot="scope">
            <span>{{ scope.row.created_at | showDateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="200">
          <template slot-scope="scope">
            <el-button plain v-permission="['product_categories.show']" @click="edit(scope.row.id)">View</el-button>
            <el-button plain v-permission="['product_categories.update']" @click="edit(scope.row.id)">Edit</el-button>

            <!--            <el-button-->
            <!--              plain-->
            <!--              type="danger"-->
            <!--              @click="del(scope.row.id)"-->
            <!--              >del</el-button-->
            <!--            >-->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>
    <div class="form">

      <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="40%">

        <el-form v-if="dialogFormVisible" ref="ruleForm" :model="formData" :rules="rules" label-position="right"
          label-width="200px">

          <el-form-item label="Parent Product Category">

            <treeselect v-model="formData.parent_id" :options="deptOptions" :normalizer="normalizer"
              @input="changeHandler" :props="{ value: 'id', label: 'pathLabel', children: 'children' }"
              placeholder="Select Category" style="width: 300px;">
              <div slot="option-label" slot-scope="{ node }" style="white-space: nowrap; font-size: 14px">
                {{ node.raw.name ? node.raw.name : '' }}
              </div>
              <div slot="value-label" slot-scope="{ node }">{{ node.raw.pathLabel ? node.raw.pathLabel : '' }}</div>
            </treeselect>

          </el-form-item>

          <el-form-item label="Category Name" prop="name">
            <el-input v-model="formData.name" placeholder="enter Name"></el-input>
          </el-form-item>

          <el-form-item label="Description" prop="note">
            <el-input v-model="formData.note" placeholder="Enter Description"></el-input>
          </el-form-item>

        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="save1('ruleForm')">Save</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import CURD from "@/mixin/CURD";
  import {
    index,
    update
  } from "@/api/product_category";
  export default {
    mixins: [CURD],
    components: {
      Treeselect
    },
    name: "product_category_index",
    data() {
      return {
        module: "product_category",
        newTitle: "Add Product Category",
        editTitle: "Edit Product Category",
        isPaginate: true,
        formData: {
          parent_id: 0,
          name: "",
          note: ""
        },
        deptOptions: []
      };
    },
    async created() {
      try {
        const {
          data
        } = await index(1, 100); // 假设index是一个异步函数
        this.categories = data;
        // 调用handleTree方法处理数据
        this.deptOptions = this.handleTree(data, "id", "parent_id");
      } catch (error) {
        console.error('Failed to fetch categories:', error);
      }

    },
    methods: {
      adda() {
        this.isNew = true;
        this.isEdit = false;
        this.formData = {
          parent_id: 0,
          name: "",
          note: ""
        }
        this.dialogFormVisible = true
        this.changeHandler(19)
      },
      async edit(id) {
        let {
          show
        } = require(`@/api/${this.module}`);
        let {
          data
        } = await show(id);
        this.formData = data;
        this.isNew = false;
        this.isEdit = true;
        this.setTitle();
        this.dialogFormVisible = true;
        this.changeHandler(this.formData.parent_id)
      },
      changeHandler(value) {
        const selectedLabel = this.getCategoryPath(value);
        console.log(selectedLabel, "最终标题");
        this.updateLabel(this.deptOptions, value, selectedLabel);
      },
      updateLabel(categories, id, label) {
        for (let category of categories) {
          if (category.id === id) {
            category.pathLabel = label;
            return;
          }
          if (category.children) {
            this.updateLabel(category.children, id, label);
          }
        }
      },
      getCategoryPath(categoryId) {
        const findCategory = (categories, id) => {
          for (let category of categories) {
            if (category.id === id) {
              return category;
            }
            if (category.children) {
              const foundCategory = findCategory(category.children, id);
              if (foundCategory) {
                return foundCategory;
              }
            }
          }
          return null;
        };

        const category = findCategory(this.deptOptions, categoryId);
        if (category) {
          let path = category.name;
          let parent = category.parent_id;
          while (parent !== null && parent !== undefined) {
            const parentCategory = findCategory(this.deptOptions, parent);
            if (parentCategory) {
              path = parentCategory.name + '/' + path;
              parent = parentCategory.parent_id;
            } else {
              break;
            }
          }
          return path;
        } else {
          return '';
        }

      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      async save1(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
                setTimeout(() => {
                  this.$router.push({
                    path: '/product/category',
                  })
                }, 1000);
              }
              if (this.isNew) {
                let {
                  store
                } = require(`@/api/${this.module}`);
                let infoaa = await store(this.formData);
                this.$message.success("Add successfully");
                setTimeout(() => {
                  this.$router.push({
                    path: '/product/category',
                  })
                }, 1000);
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
      /** 转换部门数据结构 */
      normalizer(node) {

        if (node.children && node.children.length === 0) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      handleTree(data, id, parentId, children) {
        let config = {
          id: id || 'id',
          parentId: parentId || 'parentId',
          childrenList: children || 'children'
        };

        var childrenListMap = {};
        var nodeIds = {};
        var tree = [];

        for (let d of data) {
          let parentId = d[config.parentId];
          if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
          }
          nodeIds[d[config.id]] = d;
          childrenListMap[parentId].push(d);
        }

        for (let d of data) {
          let parentId = d[config.parentId];
          if (nodeIds[parentId] == null) {
            tree.push(d);
          }
        }

        for (let t of tree) {
          adaptToChildrenList(t);
        }

        function adaptToChildrenList(o) {
          if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
          }
          if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
              adaptToChildrenList(c);
            }
          }
        }
        return tree;
      }
    }
  };
</script>

<style>
  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .avatar {
    width: 50%;
    height: 50%;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
</style>